package cn.xchats.onlinetraffic.document.server.controller;

import cn.xchats.onlinetraffic.document.server.util.PropertyUtil;
import dto.ResponseResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/*
 *
 *@author teddy
 *@date 2018/5/22
 */
@RestController
public class MenuController {

    private static final String STORE_PATH= PropertyUtil.getProperty("image.store.path");

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(@RequestParam(value = "file",required = false) MultipartFile file, ServletRequest request){
        String fileName=null;
        try {
             fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (!file.isEmpty()) {
                BufferedOutputStream out;
                File fileSourcePath = new File(STORE_PATH);
                if (!fileSourcePath.exists()) {
                    fileSourcePath.mkdirs();
                }
                //fileName = file.getOriginalFilename();
                System.out.println("上传的文件名为：" + fileName);
                out = new BufferedOutputStream(
                        new FileOutputStream(new File(fileSourcePath, fileName)));
                out.write(file.getBytes());
                out.flush();
                out.close();
                System.out.println(fileName.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ResponseResult responseResult = new ResponseResult();
        responseResult.setUrl(fileName);
        responseResult.setName(fileName);
        return JSON.toJSONString(responseResult);
    }



    @RequestMapping(value = "/getImage",method = RequestMethod.GET)
    public void getImage(HttpServletResponse response) throws IOException{
        String url="D:\\aero\\images\\01bae86d-8eb9-44be-ba65-76c9f0264b8f.jpeg";
        //读取本地图片输入流
        FileInputStream inputStream = new FileInputStream(url);
        int i = inputStream.available();
        //byte数组用于存放图片字节数据
        byte[] buff = new byte[i];
        inputStream.read(buff);
        //记得关闭输入流
        inputStream.close();
        //设置发送到客户端的响应内容类型
        response.setContentType("image/*");
        OutputStream out = response.getOutputStream();
        out.write(buff);
        //关闭响应输出流
        out.close();
    }
}
